<?php
// 应用公共文件
use think\facade\Queue;
use think\facade\Cache;
use think\facade\Config;
use general\Random;
use think\File;

/**
 * 微信消息队列-添加
 * @param array $data 传递的数据
 * @param integer $delay 延迟时间
 * @param string $task 任务名
 * @return string|boolean
 */
function add_wechat_queue($data, $delay = 0, $task = 'fire')
{
    $delay = intval($delay);
    $jobHandlerClassName = 'app\common\job\Wechat@' . $task;
    $jobQueueName = "WechatQueue";
    $jobData = $data;
    if ($delay > 0) {
        $isPushed = Queue::later($delay, $jobHandlerClassName, $jobData, $jobQueueName);
    } else {
        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
    }
    if ($isPushed !== false) {
        //记录日志
        add_queue_log($isPushed, $data, $jobHandlerClassName, $jobQueueName, $delay);
        return true;
    } else {
        return false;
    }
}

/**
 * 网站采集队列-添加
 * @param array $data 传递的数据
 * @param integer $delay 延迟时间
 * @param string $task 任务名
 * @return string|boolean
 */
function add_media_queue($data, $delay = 0, $task = 'fire')
{
    $delay = intval($delay);
    $jobHandlerClassName = 'app\common\job\Media@' . $task;
    $jobQueueName = "MediaQueue";
    $jobData = $data;
    if ($delay > 0) {
        $isPushed = Queue::later($delay, $jobHandlerClassName, $jobData, $jobQueueName);
    } else {
        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
    }
    if ($isPushed !== false) {
        //记录日志
        //add_queue_log($isPushed, $data, $jobHandlerClassName, $jobQueueName, $delay);
        return true;
    } else {
        return false;
    }
}

/**
 * 消息队列日志
 * @return boolean
 */
function add_queue_log($id, $data, $class, $queue, $delay)
{
    $model = new \app\common\model\QueueLog();
    $arrData = [
        'id' => $id,
        'class' => $class,
        'queue' => $queue,
        'payload' => json_encode($data, true),
        'execution_time' => time() + $delay,
    ];
    $model->save($arrData);
}

/**
 * 下划线转驼峰
 * @param $uncamelized_words
 * @param string $separator
 * @return string
 */
function camelize($uncamelized_words, $separator = '_')
{
    $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
    return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
}

/**
 * 驼峰转下划线
 * @param $camelCaps
 * @param string $separator
 * @return string
 */
function uncamelize($camelCaps, $separator = '_')
{
    return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
}

/**
 * 隐藏手机号中间四位 13555555555 -> 135****5555
 * @param string $mobile 手机号
 * @return string
 */
function hide_mobile(string $mobile)
{
    return substr_replace($mobile, '****', 3, 4);
}

/**
 * 将字节转换为可读文本
 * @param int $size 大小
 * @param string $delimiter 分隔符
 * @return string
 */
function format_bytes($size, $delimiter = '')
{
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 6; $i++)
        $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 格式化文件大小
 * @param int $b
 * @param number $times
 * @return string
 */
function format_size($b, $times = 0)
{
    if ($b > 1024) {
        $temp = $b / 1024;
        return format_size($temp, $times + 1);
    } else {
        $unit = 'B';
        switch ($times) {
            case '0':
                $unit = 'B';
                break;
            case '1':
                $unit = 'KB';
                break;
            case '2':
                $unit = 'MB';
                break;
            case '3':
                $unit = 'GB';
                break;
            case '4':
                $unit = 'TB';
                break;
            case '5':
                $unit = 'PB';
                break;
            case '6':
                $unit = 'EB';
                break;
            case '7':
                $unit = 'ZB';
                break;
            default:
                $unit = '单位未知';
        }
        return sprintf('%.2f', $b) . $unit;
    }
}

/**
 * 格式化数字
 * @param int $b
 * @param number $times
 * @return string
 */
function format_number($b, $times = 0)
{
    if ($b > 10000) {
        $b = $b / 10000;
        $unit = '万';
        return sprintf('%.2f', $b) . $unit;
    } elseif ($b > 1000) {
        $b = $b / 1000;
        $unit = '千';
        return sprintf('%.2f', $b) . $unit;
    } else {
        return $b;
    }
}

/**
 * 获取存储的文件名
 * @param $file File
 * @return string
 */
function get_file_savekey($file, $savekey = '')
{
    $suffix = strtolower(pathinfo($file->getOriginalName(), PATHINFO_EXTENSION));
    $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';

    $md5 = md5_file($file->getRealPath());
    $replaceArr = [
        '{year}' => date("Y"),
        '{mon}' => date("m"),
        '{day}' => date("d"),
        '{hour}' => date("H"),
        '{min}' => date("i"),
        '{sec}' => date("s"),
        '{random}' => Random::alnum(16),
        '{random32}' => Random::alnum(32),
        '{suffix}' => $suffix,
        '{.suffix}' => $suffix ? '.' . $suffix : '',
        '{filemd5}' => $md5,
    ];
    $savekey = $savekey ?: '{year}{mon}/{filemd5}{.suffix}';
    $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

    return $savekey;
}